package com.syz.mall.service.impl;

import com.syz.mall.mapper.CartMapper;
import com.syz.mall.mapper.ProductMapper;
import com.syz.mall.pojo.Cart;
import com.syz.mall.pojo.Category;
import com.syz.mall.pojo.Product;
import com.syz.mall.pojo.vo.CartVO;
import com.syz.mall.service.ICartService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class CartServiceImpl implements ICartService {
    @Autowired
    private CartMapper cartMapper;

    @Autowired
    private ProductMapper productMapper;
    @Override
    public boolean add(Cart cart) {  //这里需要事务管理
        Product product=productMapper.selectByPrimaryKey(cart.getProductId());
        int stock=product.getStock();
        //如果库存不足，直接返回失败
        if(cart.getQuantity()>stock){
            return false;
        }else{ //有库存，更新商品数量，更新失败后直接返回
            product.setStock(stock-cart.getQuantity());
            int c=productMapper.updateByPrimaryKeySelective(product);
            if(c<1){
                return false;
            }
        }
        //然后更新用户的购物车
        int cartCount = cartMapper.selectCountByUserIdAndProductId(cart);
        int count = 0;
        if (cartCount == 1) {//这个商品已经在这个用户的购物车里面，只要更新数量就可以
            count = cartMapper.updateQuantity(cart);
        } else {// 这个商品在这个用户的购物车里面没有，就直接插入
            count = cartMapper.insertSelective(cart);
        }
        return count == 1 ? true : false;
    }

    @Override
    public List<CartVO> selectByUserId(Integer id) {
        return cartMapper.selectByUserId(id);
    }

    @Override
    public boolean deleteById(Integer id) {
        int count = cartMapper.deleteByPrimaryKey(id);
        return count == 1 ? true : false;
    }

    @Override
    public boolean updateChecked(Integer id, Integer checked) {
        int count = cartMapper.updateChecked(id, checked);
        return count == 1 ? true : false;
    }

    @Override
    public List<CartVO> selectByUserIdAndChecked(Integer id) {
        return cartMapper.selectByUserIdAndChecked(id);
    }

    @Override
    public int selectCountByUserId(Integer id) {
        return cartMapper.selectCountByUserId(id);
    }

    @Override
    public boolean updateByPrimaryKeySelective(Cart record) {
        int count= cartMapper.updateByPrimaryKeySelective(record);
        return count==1;
    }
}
